package StringDemo1;

import org.junit.jupiter.api.Test;

/**
 * @Author Mr.Wen
 * @Version 1.0
 * 实现字符串反转的几种方法
 */
@SuppressWarnings("all")
public class Test2 {
    @Test
    void test1() {/*TODO 实现字符串反转的几种方法*/
        String s = "wenkehang";
        System.out.println(charAtReverse(s));
    }

    /**
     * charAt顺序遍历累加
     *
     * @param s
     * @return
     */
    public static String charAtReverse(String s) {
        int length = s.length();
        String reverse = " ";
        for (int i = 0; i < length; i++) {
            reverse = s.charAt(i) + reverse;//字符串中获取单个字符的字符的放法
            System.out.println("reverse = " + reverse);
        }
        return reverse;
    }

    /**
     * toCharArray方法+后序遍历
     *
     * @param s
     * @return
     */
    public static String reverseCharArrays(String s) {
        char[] array = s.toCharArray();//把字符串分割成单个字符的数组
        String reverse = "";
        for (int i = array.length - 1; i >= 0; i--) {//遍历数组,从后向前拼接
            reverse += array[i];
        }
        return reverse;
    }

    /**
     * StringBuffer的reverse api
     *
     * @param s
     * @return
     */
    public static String reverseStringBuffer(String s) {
        StringBuffer sb = new StringBuffer(s);
        String afterReverse = sb.reverse().toString();
        return afterReverse;
    }

    /**
     * 递归
     *
     * @param s
     * @return
     */
    public static String reverseRecursive(String s) {
        int length = s.length();
        if (length <= 1) {
            return s;
        }
        String left = s.substring(0, length / 2);
        String right = s.substring(length / 2, length);
        String afterReverse = reverseRecursive(right) + reverseRecursive(left);//此处是递归的方法调用
        return afterReverse;
    }
}
